<?php


namespace app\index\common;


use app\index\model\User;
use think\Controller;
use think\Env;
use think\Exception;

class Common extends Controller
{
    public static function paymentNotice($user,$group,$message,$action){
        try {
            $UserClass = new User();
            $user_data = $UserClass->alias('u')
                ->join('action_role ar', 'u.id=ar.user_id or u.role=ar.role_id or u.role_detail_id=ar.role_detail_id or u.group_id=ar.group_id', 'left')
                ->join('__ACTION__ a', 'ar.action_id=a.id', 'left')
                ->where(function ($query) use ($group) {
                    $query->where('u.group_id', $group)->whereOr('ar.action_type', 2);
                })
                ->where('ar.action_type', 'in', [1, 2])
                ->where('a.action_name', 'in', $action)
                ->where('u.status', 1)
                ->where('u.del_flag', 0)
                ->where('ar.del_flag', 0)
                ->where('a.del_flag', 0)
                ->group('u.id')
                ->column('u.id');
            $user_list = [];
            if (!empty($user_data)) {
                $user_list = $user_data;
            }
            $user_list[] = $user;
            $user_list=array_unique($user_list);
            return Common::sendWSMessage($user_list, 0, $message);
        }catch (Exception $e){
            trace('paymentNotice Error'.$e->getMessage(),'error');
            return false;
        }
    }

    public static function sendWSMessage($user,$ws_id,$message){
        $tcpport=Env::get('websocket.tcpPort');
        try {
            $client = stream_socket_client('tcp://127.0.0.1:'.Env::get('tcpPort',$tcpport), $errno, $errmsg, 1);
            if(!$client){
                trace('tcp error '.$errmsg,'error');
                return false;
            }
            $message['code']=0;
            $send_data = array('uid'=>$user,'ws_id'=>$ws_id, 'percent'=>json_encode($message));
            fwrite($client, json_encode($send_data)."\n");
            return fread($client, 8192);
        }catch (Exception $e){
            trace('tcp error '.$e->getMessage(),'error');
            return false;
        }
    }

    /**
     * demandStock
     * 计算需求库存
     * @url
     * @method
     * @param array $arr 库存数组
     * @param int $amount 需求数量
     * @return array
     * @author Asira
     * @date 2021/3/2
     */
    public static function demandStock($arr, $amount): array
    {
        if($arr['type']===2){
            return ['demand_stock'=>0,'stock_demand_stock'=>$arr['demand_stock'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']];
        }
        $last_stock=$arr['amount']-$arr['locked_demand_stock'];
        $stock_demand_stock=($arr['demand_stock']+$amount);
        if($last_stock>0){
            if($amount<$last_stock){
                $demand_stock=$amount;
                $stock_locked_demand_stock=($arr['locked_demand_stock']+$amount);
            }else{
                $demand_stock=$last_stock;
                $stock_locked_demand_stock=($arr['locked_demand_stock']+$last_stock);
            }
        }else{
            $demand_stock=0;
            $stock_locked_demand_stock=$arr['locked_demand_stock'];

        }
        return ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock];
    }

    /**
     * lockedStock
     * 计算需求库存和锁定库存
     * @url
     * @method
     * @param array $arr 库存数组
     * @param array $items 商品数组
     * @return array
     * @author Asira
     * @date 2021/3/6
     */
    public static function lockedStock($arr, $items): array
    {
        if ($items['type'] === 1) {
            $amount = $items['amount'] - $items['demand_stock'];
            $lock_amount=$items['amount']-$items['lock_quantity'];
        }else{
            return ['demand_stock'=>0,'stock_demand_stock'=>$arr['demand_stock'],'locked_stock'=>0,'stock_locked_stock'=>$arr['locked_quantity'],'stock_locked_demand_stock'=>$arr['locked_demand_stock']];
        }
        ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=self::demandStock($arr,$amount);
        $last_lock_quantity = $arr['amount'] - $arr['locked_quantity'];
        if ($last_lock_quantity > 0) {
            if($last_lock_quantity>=$lock_amount){
                $locked_stock=$lock_amount;
                $stock_locked_stock=$arr['locked_quantity']+$lock_amount;
            }else{
                $locked_stock=$last_lock_quantity;
                $stock_locked_stock=$arr['locked_quantity']+$last_lock_quantity;
            }
        }else{
            $locked_stock=0;
            $stock_locked_stock=$arr['locked_quantity'];
        }
        return ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'locked_stock'=>$locked_stock,'stock_locked_stock'=>$stock_locked_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock];
    }

    public static function getThumbImage($image,$width='_200X200'){
        if($image) {
            $ext = strrchr($image, '.');
            return $image . $width . $ext;
        }
        return null;
    }

    public static function getShippingPrice($price){
        $min=40;
        $stage=11;
        $min_ship_fee=25;
        if($price<=40){
            $ship_fee=25;
        }else if($price<500){
            $interval=($price-$min);
            $count=ceil($interval/30);
            $ship_fee=($stage*$count+$min_ship_fee);
        }else if($price<1000){
            $interval=($price-$min);
            $count=ceil($interval/30)+1;
            $ship_fee=ceil(($stage*$count+$min_ship_fee)/2);
        }else{
            $ship_fee=0;
        }
        return $ship_fee;
    }
}
